<?php
/**
 * 下单页面相关
 * User: lyz
 * Date: 2016/3/07
 * Time: 22:39
 */
namespace Api\Controller;

use Think\Controller;
use Api\Model\LoginModel;
use Api\Model\RepairOrderModel;

/**
 *下单推送
 */
class PushOrderController extends BaseController
{
    public function index()
    {
        $this->_getResult();
      die();
        while (True) {
            try {
                $this->_getResult();
            } catch (\Exception $e) {
                if (strpos($e->getMessage(), 'Unknown response') !== false) {
                    echo date('y-m-d h:i:s') . "rss_pop redis bug continue" . PHP_EOL;
                    continue;
                } else {
                    echo $e->getMessage();
                    echo $e->getFile() . " Line:";
                    echo $e->getLine() . "<br>";
                    echo date('y-m-d h:i:s') . " rss_pop other bug continue" . PHP_EOL;
                    continue;
                }
            }
          //  sleep(rand() % 3);
            sleep(7);
        }
        /*  $redis=S(array('type'=>'redis'));
          $orderId=$redis->lpop(C('REPAIR_ORDER_PUSH_KEY'));
          $orderId = 40;
          var_dump($orderId);*/
    }


    private function _getResult()
    {
        $redis = S(array('type' => 'redis'));
        //得到装修orderid
        $orderId = $redis->lpop(C('REPAIR_ORDER_PUSH_KEY'));
        /*
                if(!$orderId){
                    echo "111\n" ;
                    return;
                }*/
       // $orderId=168;`
        $orderMap = array();
        $RepairOrder = M('RepairOrder');
        $orderMap['repair_order_id'] = $orderId;
        $orderMap['status'] = 1;//待服务
        $orderData = $RepairOrder->where($orderMap)->find();
        if (empty($orderData)) {
            $RepairOrder->query("select now()");
            file_put_contents("/tmp/log.txt",var_export($orderData,true)."cant find order----".var_export($orderMap,true),FILE_APPEND);
            return;
            //订单不存在
        }
        $mode_charging = (int)$orderData['mode_charging'];
        $category_id = (int)$orderData['category_id'];
        //$fault_type=$orderData['fault_type'];
        $user_id = $orderData['user_id'];
        $user = M('user');
        $lng=$orderData['lng'];
        $lat=$orderData['lat'];
        //下订单的用户，距离师傅多少米
        $juli = "ROUND(6378.138*2*ASIN(SQRT(POW(SIN(({$lat}*PI()/180-lat*PI()/180)/2),2)+COS({$lat}*PI()/180)*COS(lat*PI()/180)*POW(SIN(({$lng}*PI()/180-lng*PI()/180)/2),2)))*1000) AS juli";
        $order_type = $orderData['order_type'];
        $UserMode = M('UserMode');
        $prex = C('DB_PREFIX');
//        $sql = " LEFT JOIN {$prex}user on {$prex}user.user_id={$prex}user_mode.user_id ";
//        $sql .= " where  {$prex}user.is_listen=1 and {$prex}user.role=2 ";
//        $sql .= " and {$prex}user_mode.mode_cate =1 and FIND_IN_SET('$order_type',{$prex}user_mode.mode_order) ";
//        $sql .= " and {$prex}user.is_real=1";
//        $sql .= " and FIND_IN_SET('$mode_charging',{$prex}user_mode.mode_charging) ";
        ///////测试
        $sql = " LEFT JOIN {$prex}user on {$prex}user.user_id={$prex}user_mode.user_id ";
        $sql .= " LEFT JOIN {$prex}user_repair_conf on {$prex}user_repair_conf.user_id={$prex}user.user_id ";
        //$sql .= " where  {$prex}user.is_listen=1 and {$prex}user.role=2 and ";
        $sql .= " where  {$prex}user.role=2 and ";
        $sql .= "FIND_IN_SET($order_type,{$prex}user_mode.mode_order) ";
        $sql .= " and {$prex}user.is_real=1";
        $sql .= " and {$prex}user_repair_conf.category_id=$category_id";
        $sql .= " and {$prex}user.user_id!={$orderData['user_id']}";
        $sql .= " and FIND_IN_SET($mode_charging,{$prex}user_mode.mode_charging) ";
        file_put_contents("/tmp/sql.txt",$sql."----",FILE_APPEND);
        $masterList = $UserMode
            ->field("DISTINCT {$prex}user.user_id,{$prex}user.push_name,{$prex}user.phone,{$prex}user.is_real,$juli")
            ->join(array($sql))
            ->order('juli asc')
            ->select();

        file_put_contents("/tmp/sql.txt",$UserMode->getLastSql()."----",FILE_APPEND);
        //jpush
        $pushData = array();//推送信息
        $pushData['shippingAddr'] = $orderData['shipping_addr'];
        $pushData['bookTime'] = $orderData['book_time'];
        $pushData['categoryName'] = M('category')->field('category_name')->find($orderData['category_id']);
        $pushData['faultList'] = $this->_getFailNames($orderData['fault_id_list']);
        /*category_id
        fault_type //1是标准[给出总价],2是非标准[只给出诊断费不给出总价]*/
        if ($orderData['fault_type'] == 1) {
            $pushData['price'] = $orderData['total'];
        } else {
            $pushData['diagnosis_cost'] = $orderData['diagnosis_cost'];
        }
       // $jpushObj = new \Org\Util\JPush_test();
        $pushCnt = 0;
        $pushorderModel = M('Pushorder');
        file_put_contents("/tmp/sql.txt",$masterList."----",FILE_APPEND);
        foreach ($masterList as $key => $val) {
            //要分别推送
            //写入到zsf_repair_order_push
            $map['user_id'] = $val['user_id'];
            $map['order_id'] = $orderId;
            $pushorderData=$pushorderModel->where($map)->find();
            //$pushorderData = $pushorderModel->data();
            //var_dump($pushorderData);exit;
            if (empty($pushorderData)) {
                $this->_add2PushOrder($pushorderModel, $val['user_id'], $orderId);
            }
          /*  $receive = 'all';//别名
            $content = '那个傻逼？';
            $m_type = 'tb';
            $m_txt = json_encode($pushData);
            $m_time = '600';        //离线保留时间
            $res = $jpushObj->send_pub($receive, 111, '', $m_txt, $m_time);*/
           // var_dump($res);
            if (!empty($res)) {
                $pushCnt++;
            }
        }
        $redis->lpush(C('REPAIR_ORDER') . '_' . $orderId, $masterList);//对应的抢单师傅列表
        file_put_contents("/tmp/log.txt","pushdata====".var_export(C('REPAIR_ORDER') . '_' . $orderId,true)."\r\n",FILE_APPEND);
        $pushRes=$redis->set(C('REPAIR_ORDER') . '_key_' . $orderId, 1);//抢单数量设置成1
        $redis->expire(C('REPAIR_ORDER') . '_key_' . $orderId,86400);
        //$pushRes=S(C('REPAIR_ORDER') . '_key_' . $orderId,1);
        file_put_contents("/tmp/log.txt","pushdata====".var_export($pushRes,true)."\r\n",FILE_APPEND);
        if ($pushCnt > 0) {
            $data['repair_order_id'] = $orderId;
            $data['push_cnt'] = $pushCnt;
            $res = $RepairOrder->save($data);
        }
        //REPAIR_ORDER
        //修改订单表中的推送了多少个师傅字段
        //往redis里面插入一条订单记录
        //指派下单的话，只推送给指定的师傅
        //不是指派下单，则取查找
        //查找模式设置里面的分类为装修的
        //查找模式设置里面的订单类型为对应的下单类型的
    }

    private function _add2PushOrder($model, $user_id, $order_id)
    {
        $model->user_id = $user_id;
        $model->order_id = $order_id;
        $model->status = 0;
        $flag=$model->add();
        file_put_contents("/tmp/sql.txt",$user_id."--addMaster--".$flag."----",FILE_APPEND);

    }

    /**
     * 查找故障列表对应的名字
     * @params $fids string 故障列表[id]
     */
    private function _getFailNames($fids)
    {
        $faultNameStr = '';
        $faultArr = M('fault')->where(array('fault_id' => array('in', $fids)))->field('name')->select();
        if (!empty($faultArr)) {
            foreach ($faultArr as $key => $val) {
                $faultNameStr .= ',' . $val['name'];
            }
            $faultNameStr = ltrim($faultNameStr, ',');
        }
        return $faultNameStr;
    }
}